/**
 * 
 */
package wsepForum.network.common;

import java.util.Vector;

/**
 * In charge of extract console tokens from incoming network data
 * Console tokens are lines typed by the client in console
 * @author Oren Ben-Haim
 *
 */
public class ConsoleTokenizer implements ITokenizer<ConsoleToken> {
	/*****************************
	 * MEMBERS                   *
	 *****************************/
	/**
	 * char ASCII code of a backspace signal
	 */
	private final int BACKSPACE = 8;
	/**
	 * holds a buffer to typed chars
	 */
	private StringBuffer buffer;
	
	
	/*****************************
	 * CONSTRUCTOR               *
	 *****************************/
	public ConsoleTokenizer() {
		this.buffer = new StringBuffer();
	}
	
	/*****************************
	 * METHODS                   *
	 *****************************/
	/* (non-Javadoc)
	 * @see wsepForum.domain.network.tokenizer.ITokenizer#process(java.lang.String)
	 */
	@Override
	public Vector<ConsoleToken> process(String incoming) {

		String processed = incoming.replaceFirst("\r\n", "\n");
		int backindex = -1;
		while ((backindex = processed.indexOf(BACKSPACE)) > -1) {
			if (backindex == 0) {
				if(this.buffer.length() > 0)
					this.buffer.delete(this.buffer.length()-1, this.buffer.length());
				processed = processed.substring(1);
			}
			else {
				processed = processed.substring(0,backindex-1) + processed.substring(backindex+1);
			}
		}
		this.buffer.append(processed);
		String currentBuffer = buffer.toString()+"\0";
		String[] splitted = currentBuffer.split("\n");
		
		if (splitted.length > 1) {
			Vector<ConsoleToken> answer = new Vector<ConsoleToken>(splitted.length-1);
			for (int i=0;i<splitted.length-1;i++) {
				answer.add(new ConsoleToken(splitted[i]));
			}
			this.buffer.delete(0, this.buffer.length());
			this.buffer.append(splitted[splitted.length-1].trim());
			return answer;
		}
		else {
			return null;
		}
	}

}
